package com.heima.user.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.feign.ApAuthorFeign;
import com.heima.common.constants.MQConstants;
import com.heima.common.dtos.Result;
import com.heima.common.exception.AppHttpCodeEnum;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserFollowService;
import com.heima.utils.common.ThreadLocalUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * APP用户关注信息表 服务实现类
 * </p>
 *
 * @author heima
 * @since 2021-08-06
 */
@Service
@Transactional
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements ApUserFollowService {
    @Autowired
    private ApAuthorFeign apAuthorFeign;
    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private ApUserFanMapper apUserFanMapper;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 用户关注作者
     */
    @Override
    public Result userFollow(UserRelationDto dto) {
        //判断如果用户没有登录，提示先登录
        ApUser apUser = (ApUser) ThreadLocalUtils.get();
        if (apUser == null) {
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApAuthor apAuthor = apAuthorFeign.findone(dto.getAuthorId()).getData();
        if (apAuthor == null) {
            throw new LeadNewsException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        try {
            //查询用户对象
            apUser = apUserMapper.selectById(apUser.getId());

            //判断关注还是取关
            Integer authorUserId = apAuthor.getUserId();
            QueryWrapper<ApUserFollow> followQueryWrapper = new QueryWrapper<>();
            followQueryWrapper.eq("user_Id", apUser.getId());
            followQueryWrapper.eq("follow_id", authorUserId);
            ApUserFollow userFollow = getOne(followQueryWrapper);

            QueryWrapper<ApUserFan> fanQueryWrapper = new QueryWrapper<>();

            fanQueryWrapper.eq("userId_id", authorUserId);
            fanQueryWrapper.eq("foller_id", apUser.getId());
            ApUserFan userFan = apUserFanMapper.selectOne(fanQueryWrapper);
            if (userFollow == null && userFan == null && dto.getOperation().equals(0)) {
                //新增记录

                //用户关注表记录
                userFollow = new ApUserFollow();
                userFollow.setUserId(apUser.getId());
                userFollow.setFollowId(authorUserId);
                userFollow.setFollowName(apAuthor.getName());
                userFollow.setLevel(1);
                userFollow.setIsNotice(1);
                userFollow.setCreatedTime(new Date());
                save(userFollow);

                //粉丝表
                ApUserFan apUserFan = new ApUserFan();
                apUserFan.setFansId(apUser.getId());
                apUserFan.setUserId(authorUserId);
                apUserFan.setFansName(apUser.getName());
                apUserFan.setLevel(1);
                apUserFan.setCreatedTime(new Date());
                apUserFan.setIsDisplay(1);
                apUserFan.setIsShieldLetter(0);
                apUserFan.setIsShieldComment(0);
                apUserFanMapper.insert(apUserFan);
                //只有在关注操作时，同步记录关注行为数据
                if (dto.getOperation().equals(0)){
                    FollowBehaviorDto behaviorDto = new FollowBehaviorDto();
                    behaviorDto.setUserId(apUser.getId());
                    behaviorDto.setArticleId(dto.getArticleId());
                    behaviorDto.setFollowId(authorUserId);
                    kafkaTemplate.send(MQConstants.FOLLOW_BEHAVIOR_TOPIC, JSONUtils.toJSONString(behaviorDto));
                }


            }else {
                remove(followQueryWrapper);
                apUserFanMapper.delete(fanQueryWrapper);
            }
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadNewsException(AppHttpCodeEnum.SERVER_ERROR);
        }


    }

    @Override
    public ApUserFollow findUserFollow(Integer userId, Integer followId) {
        QueryWrapper<ApUserFollow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("follow_id",followId);
        return getOne(queryWrapper);

    }
}
